﻿using IronBarCode;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace Factory.Web.Controllers
{
    /// <summary>
    /// 二维码控制器
    /// </summary>
    public class QRCodeController : Controller
    {

        private readonly IWebHostEnvironment _environment;
        public QRCodeController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }
        public IActionResult CreateQRCode()
        {
            return View();
        }
        [HttpPost]
        public IActionResult CreateQRCode(QRCodeMode generateQRCode)
        {

            try
            {
                // Creating QR Code
                GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText);
                string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string filePath = Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png");
                barcode.SaveAsPng(filePath);
                string fileName = Path.GetFileName(filePath); // qr code file
                string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/GeneratedQRCode/" + fileName;
                ViewBag.QrCodeUri = imageUrl;
            }
            catch (Exception)
            {
                throw;
            }
            return View();
        }







    }
}
